import {FunctionDecoratorType, ParameterDecoratorType} from "./types";
import {requiredVerify} from "./requiredVerify";

const paramVerifiers: FunctionDecoratorType[] = [
  requiredVerify
];

export default class Verify {
  //参数验证（默认验证必填）
  static param(types: ParameterDecoratorType[] = ['required']) {
    return function (target: Object, propertyKey: string | symbol, parameterIndex: number): void {
      for (let i = 0; i < types.length; i++) {
        const requiredList = Reflect.getMetadata(types[i], target, propertyKey) || [];
        requiredList.push(parameterIndex);
        Reflect.defineMetadata(types[i], requiredList, target, propertyKey);
      }
    }
  }

  //配合前面的参数验证来验证方法，可作用于普通方法和静态方法，不适用于构造方法。
  static fun(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor): void {
    const paramVerifyMap = new Map<ParameterDecoratorType, number[]>();
    for (let i = 0; i < paramVerifiers.length; i++) {
      paramVerifyMap.set(paramVerifiers[i].type, Reflect.getMetadata(paramVerifiers[i].type, target, propertyKey) || []);
    }
    const method = descriptor.value;
    descriptor.value = function () {
      for (let i = 0; i < paramVerifiers.length; i++) {
        paramVerifiers[i].verifyFun(paramVerifyMap.get(paramVerifiers[i].type)!, target, propertyKey, arguments);
      }
      method.apply(this, arguments);
    }
  }
}